package com.lowca.news.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.code.kaptcha.Producer;
import static com.lowca.news.constant.Constants.CAPTCHA_CONTEXT;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 输出验证码图片的控制器
 * 
 * @author konglz
 * 
 */
@Controller
public class CaptchaController {

	private static final Log log = LogFactory.getLog(CaptchaController.class);

	@Resource
	private Producer captchaProducer;

	@RequestMapping(value = "/captcha.do")
	public void captcha(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		byte[] captchaAsJpeg = null;
		// the output stream to render the captcha image as jpeg into
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			String capText = captchaProducer.createText();
			request.getSession().setAttribute(CAPTCHA_CONTEXT, capText);
			BufferedImage bi = captchaProducer.createImage(capText);
			JPEGImageEncoder jpegEncoder = JPEGCodec
					.createJPEGEncoder(jpegOutputStream);
			jpegEncoder.encode(bi);
		} catch (IllegalArgumentException e) {
			log.error(e);
		} catch (ImageFormatException e) {
			log.error(e);
		} catch (IOException e) {
			log.error(e);
		}
		captchaAsJpeg = jpegOutputStream.toByteArray();
		// flush it in the response
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream = response.getOutputStream();
		responseOutputStream.write(captchaAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	}

}